<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item
        style="display: none;"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input v-decorator="['id']"/>
      </a-form-item>

      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form-item
            style="width: 100%"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="脚本名"
            hasFeedback
          >
            <a-input placeholder="请输入脚本名"
                     v-decorator="['name', {rules: [{required: true, min: 1, message: '请输入脚本名！'}]}]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item
            label="脚本分组"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-tree-select
              v-decorator="['group', {rules: [{ required: true, message: '请选择脚本分组！' }]}]"
              style="width: 100%"
              :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
              :treeData="groupTree"
              placeholder="请选择脚本分组"
              treeDefaultExpandAll
            >
                  <span slot="title" slot-scope="{ id }">{{ id }}
                  </span>
            </a-tree-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            hasFeedback
          >
              <span slot="label">
                  <a-tooltip title="配置游戏项目脚本时需要填写">
                    <a-icon type="question-circle-o"/>
                  </a-tooltip>&nbsp;
                  项目
              </span>
            <a-select allow-clear placeholder="请选择项目" mode="combobox"
                      v-decorator="['project']">
              <a-select-option v-for="item in projectList" :key="item" :value="item">{{ item
                }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            hasFeedback
          >
              <span slot="label">
                  <a-tooltip title="配置测试服更新和推送版本包脚本时需要输入">
                    <a-icon type="question-circle-o"/>
                  </a-tooltip>&nbsp;
                  语言
              </span>
            <a-select allow-clear placeholder="请选择语言" mode="combobox"
                      v-decorator="['language']">
              <a-select-option v-for="item in languageList" :key="item" :value="item">{{ item
                }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider/>

      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        v-for="(parameters, index) in taskForm.parameters"
        :label="parameters.key + index"
        :key="parameters.key + index"
      >
        <a-card size="small">
          <a slot="extra" @click.prevent="removeParameter(parameters)">
            <a-icon style="color: red" type="close"/>
          </a>
          <a-form-model :model="taskForm.parameters[index]">
            <a-form-item
              label="参数名"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input v-model="parameters.name"></a-input>
            </a-form-item>
            <a-form-item :label="parameters.type=== 'str'?'默认值':'选项'"
                         :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <a-input v-model="parameters.value" v-if="parameters.type=== 'str'">
              </a-input>
              <a-textarea v-model="parameters.option" v-if="parameters.type=== 'option'" :rows="2"/>
            </a-form-item>
            <a-form-item label="描述"
                         :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <a-textarea v-model="parameters.desc" placeholder="请输入描述信息" :rows="3"/>
            </a-form-item>
          </a-form-model>
        </a-card>
      </a-form-item>
      <a-dropdown>
        <a-menu slot="overlay" @click="handleMenuClick">
          <a-menu-item key="str">
            字符参数
          </a-menu-item>
          <a-menu-item key="option">
            选项参数
          </a-menu-item>
        </a-menu>
        <a-button type="dashed" block>
          <a-icon type="plus"/>
          添加参数
        </a-button>
      </a-dropdown>
      <a-divider/>

      <a-form-item
        label="执行主机"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        has-feedback
      >
        <a-tree-select
          v-decorator="['host', {rules: [{ required: true, message: '请选择执行主机！' }]}]"
          style="width: 100%"
          :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
          :treeData="treeData"
          placeholder="请选择执行主机"
          treeDefaultExpandAll
        >
                  <span slot="title" slot-scope="{ id }">{{ id }}
                  </span>
        </a-tree-select>
      </a-form-item>

      <a-form-item
        style="width: 100%"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="命令"
        hasFeedback
      >
        <a-input placeholder="请输入命令"
                 v-decorator="['command', {rules: [{required: true, min: 1, message: '请输入命令！'}]}]"/>
      </a-form-item>

      <a-form-item
        style="width: 100%"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="查看日志命令"
        hasFeedback
      >
        <a-input placeholder="请输入查看日志命令"
                 v-decorator="['log_command', {message: '请输入查看日志命令'}]"/>
      </a-form-item>

    </a-form>
  </a-modal>
</template>
<script>
  import *  as api from '@/api/main/script'
  import *  as groupApi from '@/api/main/ScriptGroup'
  import *  as hostGroupApi from '@/api/main/group'
  // 导入提示信息字典
  import config from '@/config/dict'
  import lds from 'lodash'

  export default {
    name: 'sForm',
    data() {
      return {
        labelCol: {
          xs: { span: 10 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        title: '',
        taskForm: {
          parameters: []
        },
        groupTree: [],
        projectList: [],
        languageList: [],
        treeData: [],
        parameters: [],
        form: this.$form.createForm(this)
      }
    },
    methods: {
      // 初始化方法
      open(record, type) {
        this.visible = true
        if (record) {
          this.title = '编辑脚本'
        } else {
          this.title = '新增脚本'
        }
        if (record) {
          setTimeout(() => {
            this.setFormItem(record, type)
          }, 100)
        }
        this.getGroupTree()
        this.getProjectLanguageList()
        this.getHost()
      },
      setFormItem(record, type) {
        this.form.setFieldsValue(
          {
            name: record.name,
            group: record.group,
            project: record.project,
            language: record.language,
            host: record.host,
            command: record.command,
            log_command: record.log_command
          }
        )
        this.parameters = lds.cloneDeep(record.parameters)
        if (!type) {
          this.form.setFieldsValue(
            {
              id: record.id
            }
          )
        } else {
          this.title = '克隆脚本'
        }
        const scriptDetail = []
        for (const item of this.parameters) {
          if (item.type === 'option') {
            item.option = item.option.join('\n')
          }
          scriptDetail.push(item)
        }
        this.taskForm.parameters = scriptDetail
      },
      getGroupTree() {
        groupApi.getList().then(res => {
          this.groupTree = res.data.data
        })
      },
      // 获取语言、项目 list
      getProjectLanguageList() {
        api.getProjectLanguageList().then(res => {
          this.projectList = res.data.projectList
          this.languageList = res.data.languageList
        })
      },
      // 获取所有的执行主机
      getHost() {
        hostGroupApi.getList({ 'with_hosts': 1 }).then(res => {
          this.treeData = res.data.data
        })
      },
      // 添加脚本任务表单参数
      handleMenuClick(value) {
        if (value.key === 'str') {
          this.taskForm.parameters.push({
            type: 'str',
            key: '字符参数',
            name: '',
            value: '',
            desc: ''
          })
        } else if (value.key === 'option') {
          this.taskForm.parameters.push({
            type: 'option',
            key: '选项参数',
            name: '',
            option: '',
            value: '',
            desc: ''
          })
        }
      },
      // 删除脚本任务表单参数
      removeParameter(item) {
        const index = this.taskForm.parameters.indexOf(item)
        if (index !== -1) {
          this.taskForm.parameters.splice(index, 1)
        }
      },
      // [确认按钮]提交数据方法
      handleSubmit() {
        const { form: { validateFields } } = this
        validateFields((errors, values) => {
            values.parameters = this.taskForm.parameters
            if (!errors) {
              if (values.id) {
                this.message = config.msgDict[1]
                api.updateObj(values)
                  .then((res) => {
                    this._handle_response(res, values)
                  })
              } else {
                this.message = config.msgDict[0]
                api.addObj(values)
                  .then((res) => {
                    this._handle_response(res, values)
                  })
              }
            }
          }
        )
      },
      // 处理返回消息
      _handle_response(res, values) {
        if (!res.error) {
          this.$message.success(this.message['success'])
          this.handleCancel()
          this.$emit('ok', values)
        } else {
          this.$message.error(this.message['failed'] + res.error)
        }
      },
      // [取消按钮]重置数据,关闭弹框
      handleCancel() {
        this.form.resetFields()
        this.taskForm.parameters = []
        this.visible = false
      }
    }
  }
</script>
